import EchartsComponent, { MyChartOption } from '@/components/EchartsComponent';
import { ProTable, type ProColumns } from '@/components/Pro';
import {
  deviceControllerPagePcsBasicConfigOverview,
  deviceControllerPagePcsOverview,
} from '@/services/ess/deviceInfo';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { useModel } from '@@/exports';
import { useIntl } from '@umijs/max';
import { Flex } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import Styles from './CommonStyle.less';
import PieLegend from './PieLegend';

type IProps = {
  pcsViewInfo?: API.DevicePcsPie;
};
const PCSView: React.FC<IProps> = (props) => {
  const intl = useIntl();
  const chartRef = useRef(null);
  const { initialState } = useModel('@@initialState');
  const { pcsViewInfo } = props;
  const [PcsChart, setPcsChart] = useState<MyChartOption>({
    legend: {
      show: false,
      top: 100,
      right: 'right',
      icon: 'circle',
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: ['50%', '70%'],
        label: {
          position: 'center',
          formatter: `0\n${intl.formatMessage({ id: 'stationRealtimeMonitoring.totalPcs' })}`,
        },
        labelLine: { show: false },
        data: [
          {
            value: 0,
            name: intl.formatMessage({ id: 'stationRealtimeMonitoring.standby' }),
            itemStyle: { color: 'yellow' },
          },
          {
            value: 0,
            name: intl.formatMessage({ id: 'stationRealtimeMonitoring.charging' }),
            itemStyle: { color: 'green' },
          },
          {
            value: 0,
            name: intl.formatMessage({ id: 'stationRealtimeMonitoring.discharging' }),
            itemStyle: { color: 'blue' },
          },
          {
            value: 0,
            name: intl.formatMessage({ id: 'global.standby' }),
            itemStyle: { color: 'red' },
          },
          {
            value: 0,
            name: intl.formatMessage({ id: 'stationRealtimeMonitoring.other' }),
            itemStyle: { color: '#F0F1F5' },
          },
        ],
      },
    ],
  });
  const PCSColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'global.s/N' }),
      dataIndex: 'pageIndex',
      valueType: 'index',
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.deviceName' }),
      dataIndex: 'name',
      search: false,
    },
    {
      title: intl.formatMessage({ id: 'siteManage.deviceType' }),
      dataIndex: 'pcsType',
      search: false,
    },
    {
      title: intl.formatMessage({ id: 'bigdata.ratedPower' }) + '(kW)',
      dataIndex: 'power',
      search: false,
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.runningStatus' }),
      dataIndex: 'runState',
      search: false,
      valueType: 'select',
      request: async () => {
        return await fetchDictInfo(DATABASE_TYPE_ENUM.PCS_STATUS);
      },
      // render: (_, record) => {
      //   return <span></span>;
      // },
    },
    {
      title: intl.formatMessage({ id: 'equipmentMonitor.commissioningTime' }),
      dataIndex: 'modifyTime',
      search: false,
      width: 150,
    },
  ];
  const baseInfoColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'global.s/N' }),
      dataIndex: 'pageIndex',
      valueType: 'index',
    },
    {
      title: intl.formatMessage({ id: 'equipmentMonitor.manufacturer' }),
      dataIndex: 'manufacturer',
    },
    {
      title: intl.formatMessage({ id: 'equipmentMonitor.equipmentModel' }),
      dataIndex: 'deviceModel',
    },
    {
      title: intl.formatMessage({ id: 'equipmentMonitor.equipmentQuantity' }),
      dataIndex: 'deviceCount',
    },
    {
      title: 'AC(V)',
      dataIndex: 'ac',
      render: (_, record) => {
        return <span>{record?.acInfo?.ratedVol || '--'}</span>;
      },
    },
    {
      title: `${intl.formatMessage({ id: 'bigdata.ratedPower' })}(kW)`,
      dataIndex: 'ratedPower',
      render: (_, record) => {
        return <span>{record?.acInfo?.ratedPower || '--'}</span>;
      },
    },

    {
      title: intl.formatMessage({ id: 'baseInfo.pcsType' }),
      dataIndex: 'typeDesc',
      valueType: 'select',
      request: async () => {
        return await fetchDictInfo(DATABASE_TYPE_ENUM.PCS_STATUS);
      },
    },
  ];
  const selectColor = (value: string) => {
    const echartsInstance = chartRef.current.instance();
    echartsInstance.dispatchAction({
      type: 'legendToggleSelect',
      name: value,
    });
  };
  useEffect(() => {
    if (pcsViewInfo) {
      let totalSum = 0;
      Object.keys(pcsViewInfo).forEach((key) => {
        totalSum += Number(pcsViewInfo[key]?.count || 0);
      });
      setPcsChart({
        legend: {
          show: false,
          left: 480,
          top: 60,
          right: 'right',
          icon: 'circle',
          itemGap: 20,
          formatter: function (name) {
            console.log('value', name);
            return `${name}`;
          },
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['50%', '70%'],
            label: {
              position: 'center',
              formatter: [
                `{a|${totalSum}}`,
                `{b|${intl.formatMessage({ id: 'stationRealtimeMonitoring.pcsTotal' })}}`,
              ].join('\n'),
              rich: {
                a: {
                  fontSize: 18,
                },
                b: {
                  fontSize: 16,
                },
              },
            },
            labelLine: { show: false },
            data: [
              {
                value: pcsViewInfo?.standby?.rate || 0,
                name: intl.formatMessage({ id: 'stationRealtimeMonitoring.standby' }),
                itemStyle: { color: 'yellow' },
              },
              {
                value: pcsViewInfo?.charge?.rate || 0,
                name: intl.formatMessage({ id: 'stationRealtimeMonitoring.charging' }),
                itemStyle: { color: 'green' },
              },
              {
                value: pcsViewInfo?.discharge?.rate || 0,
                name: intl.formatMessage({ id: 'stationRealtimeMonitoring.discharging' }),
                itemStyle: { color: 'blue' },
              },
              {
                value: pcsViewInfo?.stewing?.rate || 0,
                name: intl.formatMessage({ id: 'global.fault' }),
                itemStyle: { color: 'red' },
              },
              {
                value: pcsViewInfo?.other?.rate || 0,
                name: intl.formatMessage({ id: 'stationRealtimeMonitoring.other' }),
                itemStyle: { color: '#F0F1F5' },
              },
            ],
          },
        ],
      });
    }
  }, [pcsViewInfo]);
  return (
    <>
      <ProTable
        style={{ marginBottom: '10px' }}
        title={() => {
          return (
            <div className={Styles.tableTitle} style={{ marginLeft: '-10px' }}>
              {' '}
              {intl.formatMessage({ id: 'equipmentMonitor.basicConfigurationFile' })}
            </div>
          );
        }}
        params={{
          stationId: initialState?.stationId,
        }}
        // dataSource={pcsConfigInfo?.records}
        search={false}
        columns={baseInfoColumns}
        rowKey={'pageIndex'}
        request={deviceControllerPagePcsBasicConfigOverview}
      ></ProTable>
      <div className={Styles.divider}></div>
      <div className={Styles.tableTitle} style={{ marginTop: '10px' }}>
        {intl.formatMessage({ id: 'equipmentMonitor.realTimeCollectionOverview' })}
      </div>
      <Flex style={{ height: '18rem' }}>
        <EchartsComponent
          ref={chartRef}
          option={PcsChart}
          width={'25rem'}
          height={'18rem'}
        ></EchartsComponent>
        <div style={{ lineHeight: '9rem' }}>
          <PieLegend pcsViewInfo={pcsViewInfo} selectColor={selectColor} />
        </div>
      </Flex>
      <ProTable
        rowKey={'pageIndex'}
        columns={PCSColumns}
        search={false}
        params={{
          stationId: initialState?.stationId,
        }}
        // dataSource={pcsRealTimeInfo?.records}
        request={deviceControllerPagePcsOverview}
      ></ProTable>
    </>
  );
};

export default PCSView;
